// Copyright (c) 2021, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Tests importing, exporting, and manipulating global variables.
import 'dart:typed_data';

import 'package:test/test.dart';
import 'package:wasm/wasm.dart';

import 'test_shared.dart';

void main() {
  test('globals', () {
    // int32_t foo = 37;
    // extern const int32_t bar;
    // int32_t baz() { return foo * bar; }
    var data = Uint8List.fromList([
      0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x05, 0x01, 0x60, //
      0x00, 0x01, 0x7f, 0x02, 0x0c, 0x01, 0x03, 0x65, 0x6e, 0x76, 0x03, 0x62,
      0x61, 0x72, 0x03, 0x7f, 0x00, 0x03, 0x02, 0x01, 0x00, 0x04, 0x04, 0x01,
      0x70, 0x00, 0x00, 0x05, 0x03, 0x01, 0x00, 0x01, 0x06, 0x06, 0x01, 0x7f,
      0x01, 0x41, 0x25, 0x0b, 0x07, 0x16, 0x03, 0x06, 0x6d, 0x65, 0x6d, 0x6f,
      0x72, 0x79, 0x02, 0x00, 0x03, 0x62, 0x61, 0x7a, 0x00, 0x00, 0x03, 0x66,
      0x6f, 0x6f, 0x03, 0x01, 0x0a, 0x09, 0x01, 0x07, 0x00, 0x23, 0x01, 0x23,
      0x00, 0x6c, 0x0b, 0x0b, 0x0a, 0x01, 0x00, 0x41, 0x0c, 0x0b, 0x04, 0x25,
      0x00, 0x00, 0x00,
    ]);

    final builder = wasmModuleCompileSync(data).builder();
    final bar = builder.addGlobal('env', 'bar', 10);
    final inst = builder.build();
    final foo = inst.lookupGlobal('foo')!;
    final baz = inst.lookupFunction('baz');

    expect(foo.value, 37);
    expect(bar.value, 10);
    expect(baz(), 370);

    foo.value = 99;
    expect(foo.value, 99);
    expect(baz(), 990);

    expect(
      () => bar.value = 100,
      throwsWasmError(startsWith("Can't set value of const global")),
    );
    expect(
      () => foo.value = 3.14159,
      throwsWasmError(startsWith('Bad value for WASM type')),
    );
  });
}
